package org.yy.umflutter;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.flutter.BuildConfig;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** UmflutterPlugin */
public class UmflutterPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private Context context;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "umflutter");
    channel.setMethodCallHandler(this);
    context = flutterPluginBinding.getApplicationContext();
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    switch (call.method){
      case "init":
        UMConfigure.init(context, call.<String>argument("appKey"),call.<String>argument("channel"),UMConfigure.DEVICE_TYPE_PHONE, null);
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.LEGACY_MANUAL);
        result.success(true);
        break;
      case "exit":
        MobclickAgent.onKillProcess(context);
        result.success(true);
        break;
      case "pageStart":
        MobclickAgent.onPageStart(call.<String>arguments());
        result.success(true);
        break;
      case "pageEnd":
        MobclickAgent.onPageEnd(call.<String>arguments());
        result.success(true);
        break;
      case "signIn":
        MobclickAgent.onProfileSignIn(call.<String>arguments());
        result.success(true);
        break;
      case "signOff":
        MobclickAgent.onProfileSignOff();
        result.success(true);
        break;
      case "event":
        Map<String,String> map = call.<Map>arguments();
        String event = map.get("event");
        map.remove("event");
        if(map.keySet().isEmpty()){
          MobclickAgent.onEvent(context,event);
        } else {
          MobclickAgent.onEvent(context,event,map);
        }
        result.success(true);
        break;
      default:
        result.notImplemented();
        break;
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }
  
}
